package com.spx.core.handlers;

import org.apache.commons.lang.StringUtils;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.handlers.HandlerUtil;

import com.spx.kernel.KernelActivator;
import com.spx.kernel.types.ModelType;

/**
 * Our sample handler extends AbstractHandler, an IHandler base class.
 * 
 * @see org.eclipse.core.commands.IHandler
 * @see org.eclipse.core.commands.AbstractHandler
 */
public class RenameHandler extends AbstractHandler
{
	/**
	 * The constructor.
	 */
	public RenameHandler()
	{
	}

	/**
	 * the command has been executed, so extract extract the needed information
	 * from the application context.
	 */
	public Object execute(ExecutionEvent event) throws ExecutionException
	{
		final IStructuredSelection selection = getSelection(event);

		for (final Object object : selection.toArray())
		{
			if (object instanceof ModelType)
			{
				final Shell shell = HandlerUtil.getActiveWorkbenchWindow(event).getShell();
				final ModelType model = (ModelType) object;
				final InputDialog dialog = new InputDialog(shell, "", "Enter New Name", model.getName(), null);
				dialog.open();

				final String newName = StringUtils.trim(dialog.getValue());
				if (StringUtils.isBlank(newName) == false && StringUtils.equals(newName, model.getName()) == false)
				{
					if (KernelActivator.getDefault().getPersistService().findByName(newName) != null)
					{
						final Status status = new Status(IStatus.ERROR, "My Plug-in ID", 0, "Name Exists", null);

						ErrorDialog.openError(shell, "Name Exists", "Canot Rename", status);

						// /ERROR Dialog;
					} else
					{

						KernelActivator.getDefault().getPersistService().rename(model, newName);
					}
				}

			}

		}
		return null;
	}

	private IStructuredSelection getSelection(ExecutionEvent event)
	{
		final IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getCurrentSelection(event);
		return selection;
	}
}
